﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JCTimes.DomainModel.Repository;
using JCTimes.DomainModel.Views;
using JCTimes.DomainModel.Entity;
using JCTimes.Portal.Infrastructure;
using JCTimes.Portal.Models;
using JCTimes.Portal.Specification;
using System.Data;
using System.IO;

namespace JCTimes.Portal.Controllers
{
    [Permission]
    public class ExpressClassController : Controller
    {
        private IExpressClassRepository ecRep = null;
        private const int pageSize = 10;

        public ExpressClassController(IExpressClassRepository ecRep)
        {
            this.ecRep = ecRep;
        }

        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// Query users.
        /// </summary>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter conditions.</param>
        /// <returns>Users grid view</returns>
        public PartialViewResult Grid(int? pageIndex, Searcher searcher)
        {
            UserInfo uinfo = SessionHelper.CurrUser;
            if (uinfo.RoleID == Constant.Admin)
            {
                var model = new GridView<ExpressClass>
                {
                    Searcher = searcher,
                    PagedList = ecRep.GetList<ExpressClass>().OrderByDescending(u => u.CreateDate).ToPagedList(pageIndex ?? 1, pageSize)
                };
                return PartialView("_gridview", model);
            }
            else
            {
                var model = new GridView<ExpressClass>
                {
                    Searcher = searcher,
                    PagedList = ecRep.GetList<ExpressClass>().Where(m=>m.UsersID==uinfo.UserID).OrderByDescending(u => u.CreateDate).ToPagedList(pageIndex ?? 1, pageSize)
                };
                return PartialView("_gridview", model);
            }
        }

        public ActionResult Create()
        {
            return View(new ExpressClass { ID = Guid.NewGuid().ToString() });
        }

        /// <summary>
        /// Add user.
        /// </summary>
        /// <param name="user">User item</param>
        /// <returns>Add result in json</returns>
        [HttpPost]
        public JsonResult Create(ExpressClass ec)
        {
            try
            {
                UserInfo uinfo = SessionHelper.CurrUser;
                ec.CreateDate = DateTime.Now;
                ec.UsersID = uinfo.UserID;
                ecRep.Add(ec);
                ecRep.SaveChanges();
                return Json(new { Msg = "添加成功", IsSuccess = true });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return Json(new { Msg = "出错了" });
            }
        }

        /// <summary>
        /// Delete user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter conditions</param>
        /// <returns></returns>
        public RedirectToRouteResult Delete(string id, int pageIndex, Searcher searcher)
        {
            try
            {
                var ec = ecRep.Find(id);
                ecRep.Delete(ec);
                ecRep.SaveChanges();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
            }
            return RedirectToAction("Grid", new { pageIndex = pageIndex, searcher = searcher });
        }

        /// <summary>
        /// Edit user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter condtions.</param>
        /// <returns>User form.</returns>
        public ActionResult Edit(string id, int pageIndex, Searcher searcher)
        {
            TempData["pageIndex"] = pageIndex;
            TempData["searcher"] = searcher;
            //ViewBag.pageIndex = pageIndex;
            //ViewBag.searcher = searcher;
            return View(ecRep.Find(id));
        }

        /// <summary>
        /// Edit user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="forms">Form collections about user item.</param>
        /// <returns>Edit result, if success then redirect to list, else show validation errors.</returns>
        [HttpPost]
        public ActionResult Edit(string id, FormCollection forms)
        {
            var model = ecRep.Find(id);
            if (TryUpdateModel(model))
            {
                try
                {
                    ecRep.SaveChanges();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(ex.Message, ex);
                }
                return RedirectToAction("Index");
            }
            return View(model);
        }

        /// <summary>
        /// Bulk import modelinfo page.
        /// </summary>
        /// <returns>import page</returns>
        public ActionResult Import()
        {
            return View();
        }

        /// <summary>
        /// Post an external file as modelinfo data source and store in database.
        /// </summary>
        /// <param name="excelFile">excel file recorded modelinfo data</param>
        /// <returns>Excel file to show manipulating result if success,or show error message.</returns>
        [HttpPost]
        public ActionResult Import(HttpPostedFileBase excelFile)
        {
            if (excelFile == null)
            {
                TempData["Msg"] = "请选择文件";
                return View();
            }
            string errMsg;
            string[] excelColumns = new string[] {
                "快递类别名称"
            };
            DataTable dt;
            if (!ExcelHelper.Read(excelFile, excelColumns, out dt, out errMsg))
            {
                TempData["Msg"] = errMsg;
                return View();
            }
            else
            {
                dt.Columns.Add(new DataColumn("Result")); //add new column to record import result
                UserInfo uinfo = SessionHelper.CurrUser;

                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["快递类别名称"] == null)
                    {
                        dr["Result"] = "快递类别名称为空";
                        continue;
                    }

                    string expressclassname = Convert.ToString(dr["快递类别名称"]).Trim();
                    try
                    {                 // add new modelinfo
                        var model = new ExpressClass
                        {
                            ID = Guid.NewGuid().ToString(),
                            ExpressClassName = expressclassname,
                            UsersID = uinfo.UserID,
                            CreateDate = DateTime.Now
                        };
                        ecRep.Add(model);
                        ecRep.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        string exMsg = "导入快递类别出错";
                        dr["Result"] = "失败:" + exMsg;
                        LogHelper.WriteLog(ex.Message, ex);
                        continue;
                    }

                    dr["Result"] = "成功";
                }
            }
            byte[] fileContents = ExcelHelper.Write(dt, ExcelTemplate.ExpressClass);
            return File(fileContents, "application/vnd.ms-excel", "快递类别导入结果.xls");
        }

        /// <summary>
        /// Get the template file for modelinfo
        /// </summary>
        /// <returns>Download template file to local, or direct to error view if file does not exist.</returns>
        public ActionResult GetTemplate()
        {
            string excelName = "ExpressClass.xls";
            string fileName = Path.Combine(Server.MapPath("~/Excels/Templates"), excelName);
            if (System.IO.File.Exists(fileName))
            {
                return File(fileName, "application/vnd.ms-excel", excelName);
            }
            else
            {
                return View("FileNotExist");
            }
        }
    }
}
